﻿using System;
using System.Collections.Generic;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Commons.Interfaces.WeiXin;
using Atmk.WaterMeter.MIS.Commons.ViewModels.WeiXin;
using Newtonsoft.Json;
using RestSharp;

namespace Atmk.WaterMeter.MIS.Pay.WeiXin.Logic
{
    public class WxLogin : IWxLogin
    {
        /// <summary>
        /// 登录凭证校验：
        /// 通过微信小程序获得临时登录凭证，调用code2Session完成登录流程。
        /// </summary>
        /// <param name="appid">小程序id</param>
        /// <param name="secret">小程序appSecret</param>
        /// <param name="code">临时登录凭证</param>
        /// <returns></returns>
        public async Task<ResponCode2Session> LoginCode2Session(string appid, string secret,string code)
        {
            var resoure =
                $"sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code";
            var request = new RestRequest(resoure, Method.GET);
            var _client =
                new RestClient(WxUrlManage.Urlcode2Session)
                {
                    RemoteCertificateValidationCallback = ValidateServerCertificate
                };
            var response  = await _client.ExecuteTaskAsync(request);
            var result = JsonConvert.DeserializeObject<ResponCode2Session>(response.Content);

            return result;
        }
        private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    }
}